<template>
  <div style="background-color: #fff">
    <van-row v-show="fail_reason && used_userId == userId && status == 2">
      <van-col
        style="background-color: #fff; color: red; padding: 0 16px"
        span="24"
        >审核不通过原因：{{ fail_reason }}</van-col
      >
    </van-row>
    <van-cell-group>
      <van-field
        placeholder="二手转让产品名称(3~14个字)"
        :maxlength="14"
        v-model="title"
        required
      >
        <span slot="label">输入标题：</span>
      </van-field>
      <van-field label="工具类型：" required>
        <van-dropdown-menu
          class="my_select"
          slot="input"
          style="height: 24px"
          active-color="#EE3F00"
        >
          <van-dropdown-item
            v-model="in_class"
            :options="classoptions"
            @change="classChange"
          />
        </van-dropdown-menu>
      </van-field>
      <van-field label="新旧程度：">
        <van-dropdown-menu
          class="my_select"
          slot="input"
          style="height: 24px"
          active-color="#EE3F00"
        >
          <van-dropdown-item v-model="new_level" :options="leveloptions" />
        </van-dropdown-menu>
      </van-field>
      <van-field label="所在地区：" @click="showPopup" required>
        <span slot="input">{{ address == '' ? '请选择地区' : address }}</span>
      </van-field>
      <!-- <van-field placeholder="请填写机器数量()台" type="number">
        <span slot="label">选择数量：</span>
        <van-stepper slot="input" v-model="num" step="1" />
      </van-field> -->
      <van-field label="是否包邮：" type="number" class="is_package">
        <van-radio-group v-model="is_pinkage" slot="input">
          <van-radio
            :name="0"
            icon-size="16px"
            checked-color="#EE3F00"
            style="float: left; justify-content: center"
            >包邮</van-radio
          >
          <van-radio
            :name="1"
            icon-size="16px"
            checked-color="#EE3F00"
            style="margin-left: 10px; float: left; justify-content: center"
            >到付</van-radio
          >
        </van-radio-group>
      </van-field>
      <div
        class="van-cell van-field is_package"
        @click="checkIscertificate"
        style="display: flex; flex-direction: column"
      >
        <div style="width: 100%; display: flex; flex-direction: row">
          <div class="van-cell__title van-field__label">
            <span>平台认证：</span>
          </div>
          <div class="van-cell__value">
            <div class="van-field__body">
              <van-radio-group v-model="is_certificate" slot="input">
                <van-radio
                  :name="1"
                  icon-size="16px"
                  checked-color="#EE3F00"
                  style="float: left; justify-content: center"
                  >认证</van-radio
                >
                <van-radio
                  :name="0"
                  icon-size="16px"
                  checked-color="#EE3F00"
                  style="
                    margin-left: 10px;
                    float: left;
                    justify-content: center;
                  "
                  >不认证</van-radio
                >
              </van-radio-group>
            </div>
          </div>
        </div>
        <div
          v-if="is_certificate == 1"
          style="
            height: 40px;
            padding: 8px 0;
            color: #ee3f00;
            font-size: 12px;
            line-height: 14px;
          "
        >
          认证设备有官方认证推荐、更好保障二手交易达成;
          <br />认证设备需要返厂维修和保养，需要产生一定费用。
        </div>
        <div
          v-else
          style="
            padding: 8px 0;
            color: #ee3f00;
            font-size: 12px;
            line-height: 14px;
          "
        >
          <!--          非认证设备具体情况需要真实描述，自行了解;-->
          <!--          <br />非认证设备交易存在风险，结果双方自行承担。-->

          认证--需自行联系厂家、设备返厂检测，检测合格后此条信息展示。<br /><br />
          非认证--信息展示但无法核实真实情况要谨慎，双方自行承担结果。
        </div>
      </div>
      <van-field
        placeholder="请填写价格"
        type="number"
        v-model="price"
        required
      >
        <!-- <span slot="label">价&#12288;&#12288;格：</span>-->
        <span slot="label">二手价格：</span>
      </van-field>
      <!-- <van-field
        placeholder="请填写入手价格"
        label="入手价格："
        v-model="src_price"
        type="number"
      />-->

      <van-field
        v-if="userLevel == 2"
        label="客户电话："
        placeholder="请输入手机号"
        type="tel"
        v-model="tel"
      />
      <!-- <van-field label="二手详情：" disabled /> -->
      <!-- <div
        style="
          margin: 10px 16px;
          border: 1px solid #ebedf0;
          background-color: #fff;
          margin-bottom: 20px;
        "
      >
        <van-field
          class="useddetail"
          v-model="detail"
          rows="2"
          autosize
          type="textarea"
          maxlength="500"
          placeholder="详情介绍:
  请输入二手详情(使用情况、产品优点、使用说明、注意事项等)
  提醒:手机号码等其他联系方式无法展现"
          show-word-limit
        />
      </div>-->
      <div style="">
        <p style="font-size: 12px; color: red; margin-left: 7px">
         <span style="color:red">*</span> 请从手机相册选择图片上传，上传图片排名更靠前
        </p>
        <van-uploader
          :max-count="1"
          v-model="fileList"
          style="padding: 10px 16px"
          v-show="show_upload"
          :before-read="beforeRead"
          :after-read="afterRead"
          :before-delete="beforeDelete"
          upload-text="上传产品实图"
        />
      </div>

      <!-- <span style="display: inline-block; width: 100%; text-align: center">
        <van-button style="border: 1px solid #ee3f00" @click="uploadImg">
          <font color="#EE3F00">上传图片</font>
        </van-button>
      </span>
      <span style="
          display: inline-block;
          width: 100%;
          text-align: left;
          font-size: 13px;
          color: #95969f;
          margin-top: 10px;
          margin-bottom: 20px;
          padding: 0 16px;
        ">温馨提示：记得上传图片让您的动态更靠前哦！(可上传：产品照片、使用说明、配套说明等)
        <time-ino type="used" /></span> -->

      <div style="padding: 10px 16px; color: #ee3f00">
        <span style="display: inline-block">
          <van-checkbox
            v-model="TermsOfService"
            shape="square"
            checked-color="#07c160"
          ></van-checkbox>
        </span>
        <span
          v-if="is_certificate"
          :style="{ color: !TermsOfService ? '#ccc8c8' : '#EE3F00' }"
          class="have_read_protocol"
        >
          &ensp;已阅读并同意
          <span @click="showProtocol">《喷喷涂涂二手市场用户协议》</span>
        </span>
        <span
          v-else
          :style="{ color: !TermsOfService ? '#ccc8c8' : '#EE3F00' }"
          class="have_read_protocol"
        >
          &ensp;已阅读并同意
          <span @click="showProtocol">《喷喷涂涂二手市场用户协议》</span>
        </span>
      </div>
      <div style="padding: 0 16px">
        <van-button
          :style="{ backgroundColor: !TermsOfService ? '#ccc8c8' : '#EE3F00' }"
          style="width: 100%; color: #fff; font-size: 18px"
          @click="savePublish"
          >确认发布</van-button
        >
      </div>
      <van-popup v-model="show" position="bottom">
        <van-area
          :area-list="areaList"
          @confirm="addConfirm"
          @cancel="hidePopup"
          :value="addrCode"
        />
      </van-popup>

      <van-popup v-model="showprotocol" style="border-radius: 10px">
        <protocol v-if="is_certificate" @agree-protocol="agreeProtocol" />
        <protocol v-else @agree-protocol="agreeProtocol" />
      </van-popup>
    </van-cell-group>
  </div>
</template>
<script>
import timeIno from '@/views/info/timeIno';
import areaList from '@/views/user/module-address-edit/area_all.json';
import {
  Field,
  Button,
  Popup,
  Area,
  Stepper,
  Uploader,
  Toast,
  DropdownMenu,
  DropdownItem,
  RadioGroup,
  Radio,
  Row,
  Col,
  Checkbox,
  CheckboxGroup,
  Dialog,
} from 'vant';
import {
  storageUpload,
  usedSave,
  usedDetail,
  usedUpdate,
  dicItems,
  authInfo,
} from '@/api/api';
import { setLocalStorage } from '@/utils/local-storage';
import Protocol from '@/views/protocol/index';
import lrz from 'lrz';

export default {
  name: 'used-publish',
  props: {
    usedId: {
      type: [String, Number],
      default: -1,
    },
  },
  data() {
    return {
      userLevel: 0,
      tel: '',
      is_pinkage: 0,
      is_certificate: 0,
      is_pinkage_text: ['包邮', '到付'],
      title: '',
      in_class: -1,
      classoptions: [],
      num: 1,
      new_level: 5,
      leveloptions: [],
      areaList: areaList,
      show: false,
      showprotocol: false,
      price: '',
      src_price: '',
      province_code: '',
      province: '',
      addrCode: '321300',
      city_code: '',
      city: '',
      district_code: '',
      district: '',
      address: '',
      detail: '',
      fileList: [],
      show_upload: true,
      TermsOfService: false,
      images: [],
      mobile: '',
      userId: '',
      classId: 'USED.PUBLISH.CLASS',
      newLevelId: 'USED.PUBLISH.NEW.LEVEL',
      fail_reason: '',
      used_userId: '',
      status: -1,
    };
  },
  created() {
    this.initClassOption();
    this.initNewLevelOption();
    this.refreshUserInfo();
    if (this.usedId != -1) {
    }
    this.init();
  },
  methods: {
    agreeProtocol(data) {
      if (data == 1) {
        this.TermsOfService = data;
      }
      this.showprotocol = false;
    },
    refreshUserInfo() {
      authInfo().then((res) => {
        this.userId = res.data.data.userId;
        this.mobile = res.data.data.mobile;
        let status = res.data.data.status;
        this.userLevel = res.data.data.userLevel;
        if (status == 0) {
        } else {
          setLocalStorage({
            userId: this.userId,
            mobile: this.mobile,
          });
        }
      });
    },
    showProtocol() {
      if (this.showprotocol) {
        this.showprotocol = false;
      } else {
        this.showprotocol = true;
      }
    },
    initClassOption() {
      dicItems({
        groupId: this.classId,
      })
        .then((res) => {
          let list = res.data.data.list;
          for (let i in list) {
            let opiton = {
              text: list[i].itemName,
              value: parseInt(list[i].itemValue),
            };
            this.classoptions.push(opiton);
          }
        })
        .catch(() => {});
    },
    initNewLevelOption() {
      dicItems({
        groupId: this.newLevelId,
      })
        .then((res) => {
          let list = res.data.data.list;
          for (let i in list) {
            let opiton = {
              text: list[i].itemName,
              value: parseInt(list[i].itemValue),
            };
            this.leveloptions.push(opiton);
          }
        })
        .catch(() => {});
    },
    classChange() {
      if (this.in_class == 0) {
        //喷涂设备默认认证
        this.is_certificate = 1;
      } else {
        this.is_certificate = 0;
      }
    },
    checkIscertificate() {
      if (this.in_class == -1) {
        Toast('请选择工具类型！');
        this.is_certificate = 0;
        return;
      }
      if (this.in_class != 0 && this.is_certificate == 1) {
        Toast('只有喷涂设备可以认证！');
        this.is_certificate = 0;
      }
    },
    init() {
      usedDetail({
        usedId: this.usedId,
      })
        .then((res) => {
          this.type = res.data.data.type;
          this.title = res.data.data.title;
          this.in_class = res.data.data.inClass;
          this.district_code = res.data.data.areaCode;
          this.addrCode = res.data.data.areaCode;
          this.district = res.data.data.areaName;
          this.address = this.getAddressByDistrictCode(res.data.data.areaCode);
          this.num = res.data.data.num;
          this.price = res.data.data.price;
          this.src_price = res.data.data.srcPrice;
          this.new_level = res.data.data.newLevel;

          this.is_pinkage = res.data.data.postage;
          if (res.data.data.isCertificate) {
            this.is_certificate = 1;
          } else {
            this.is_certificate = 0;
          }
          this.detail = res.data.data.detail;
          this.images = res.data.data.images;
          this.tel = res.data.data.tel;
          this.fail_reason = res.data.data.failReason;
          this.used_userId = res.data.data.userId;
          this.status = res.data.data.status;

          this.initImgs();
          //查询detail完成后加载更多执行
        })
        .catch((e) => {});
    },
    initImgs() {
      for (let i in this.images) {
        let file = {
          url: this.images[i],
        };
        this.fileList.push(file);
        this.show_upload = true;
      }
    },
    getAddressByDistrictCode(district_code) {
      if (
        district_code == undefined ||
        district_code == null ||
        district_code == ''
      ) {
        return '地区未知';
      }
      let province_code = district_code.substring(0, 2) + '0000';
      let city_code = district_code.substring(0, 4) + '00';
      let province_name = areaList.province_list[province_code];
      let city_name = areaList.city_list[city_code];
      let district_name = areaList.county_list[district_code];
      return province_name + city_name + district_name;
    },
    addConfirm(e) {
      this.show = false;
      this.province_code = e[0].code;
      this.city_code = e[1].code;
      this.district_code = e[2].code;
      this.province = e[0].name;
      this.city = e[1].name;
      this.district = e[2].name;
      this.address = this.province + this.city + this.district;
      if (this.province_code == '100000') {
        this.address = this.province;
      }
    },
    showPopup() {
      this.show = true;
    },
    hidePopup() {
      this.show = false;
    },
    focusprc(event) {
      event.currentTarget.value = '';
    },
    // 开始
    uploadImg() {
      if (this.fileList.length > 1) return Toast('请上传2张以内的图片');
      this.show_upload = true;
      document.querySelector('.van-uploader__input').click();
    },
    beforeRead(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterRead(file) {
      //文件读取完成后的回调函数
      let that = this;
      file.status = 'uploading';
      file.message = '上传中...';
      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            file.status = 'done';
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行

            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            file.status = 'failed';
            file.message = '压缩失败';
            //失败时执行
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeDelete(file, detail) {
      this.images.splice(detail.index, 1);
      return true;
    },
    validate() {
      if (this.title.length < 3 || this.title.length > 20) {
        Toast('请输入标题(3~20个字)！');
        return false;
      }
      if (this.images.length == 0) {
        Toast('请上传图片！');
        return false;
      }
      if (this.in_class == -1) {
        Toast('请选择工具类型！');
        return false;
      }
      if (this.address == '') {
        Toast('请选择所在地区！');
        return false;
      }
      if (this.in_class != 0 && this.is_certificate == 1) {
        Toast('只有喷涂设备可以认证！');
        this.is_certificate = 0;
        return false;
      }
      if (this.price == '' || this.price <= 0) {
        Toast('请输入正确的二手价格！');
        return false;
      }
      if (this.userLevel == 2) {
        if (!this.verifyTel(this.tel)) {
          Toast('请输入正确的客户电话！');
          return false;
        }
      }
      return true;
    },
    verifyTel(tel) {
      return tel.length === 11;
    },
    savePublish() {
      //正则验证 begin
      let val = this.detail.replace(/\s*/g, '');
      let reg_telephone_CN =
        /['零',0]['零',0,'一',1,'①','壹','二',2,'②','贰','三',3,'③','叁','四',4,'④','肆','五',5,'⑤','伍','六',6,'⑥','陆','七',7,'⑦','柒','八',8,'⑧','捌','九',9,'⑨',玖]{2,3}-?['零',0,'一',1,'①','壹','二',2,'②','贰','三',3,'③','叁','四',4,'④','肆','五',5,'⑤','伍','六',6,'⑥','陆','七',7,'⑦','柒','八',8,'⑧','捌','九',9,'⑨',玖]{6,}/g;
      let reg_mobile_CN =
        /['一',1,'①','壹']['零',0,'一',1,'①','壹','二',2,'②','贰','三',3,'③','叁','四',4,'④','肆','五',5,'⑤','伍','六',6,'⑥','陆','七',7,'⑦','柒','八',8,'⑧','捌','九',9,'⑨',玖]{10}/g;
      let reg_keywords = /联系方式|电话号码/g;
      if (reg_telephone_CN.test(val)) {
        Dialog.alert({
          title: '发布失败',
          message: '详情介绍 中禁止填写电话号码',
        }).then(() => {
          // on close
          return false;
        });
        return false;
      } else if (reg_mobile_CN.test(val)) {
        Dialog.alert({
          title: '发布失败',
          message: '详情介绍 中禁止填写手机号码',
        }).then(() => {
          // on close
          return false;
        });
        return false;
      } else if (reg_keywords.test(val)) {
        Dialog.alert({
          title: '发布失败',
          message: '详情介绍 中有不被允许的关键字',
        }).then(() => {
          // on close
          return false;
        });
        return false;
      }
      //正则验证 end
      if (!this.TermsOfService) {
        Toast('请先阅读并同意喷喷涂涂二手市场用户协议！');
        return;
      }
      if (!this.validate()) {
        return;
      }
      this.tel = this.tel.replace(/\s*/g, '');
      if (this.tel != null && this.tel.length == 11) {
        this.mobile = this.tel;
      }
      if (this.usedId != -1) {
        usedUpdate({
          id: this.usedId,
          title: this.title,
          inClass: this.in_class,
          num: this.num,
          newLevel: this.new_level,
          detail: this.detail,
          price: this.price,
          srcPrice: this.src_price,
          postage: this.is_pinkage,
          isCertificate: this.is_certificate,
          areaCode: this.district_code,
          areaName: this.district,
          images: this.images,
          tel: this.mobile,
          status: 1,
        })
          .then((res) => {
            Toast('发布成功，请等待审核！');
            this.$router.go(-1);
          })
          .catch(() => {
            Toast('发布失败，请联系管理员！');
          });
      } else {
        usedSave({
          title: this.title,
          inClass: this.in_class,
          num: this.num,
          newLevel: this.new_level,
          detail: this.detail,
          price: this.price,
          srcPrice: this.src_price,
          postage: this.is_pinkage,
          isCertificate: this.is_certificate,
          areaCode: this.district_code,
          areaName: this.district,
          images: this.images,
          tel: this.mobile,
        })
          .then((res) => {
            Toast('发布成功，请等待审核！');
            this.$router.push({
              path: '/info/my-used?userId=' + this.userId,
            });
          })
          .catch(() => {
            Toast('发布失败，请联系管理员！');
          });
      }
    },
  },

  components: {
    [Field.name]: Field,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Area.name]: Area,
    [Stepper.name]: Stepper,
    [Uploader.name]: Uploader,
    [Toast.name]: Toast,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Row.name]: Row,
    [Col.name]: Col,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Protocol.name]: Protocol,
    [Dialog.Component.name]: Dialog.Component,
    timeIno,
  },
};
</script>
<style lang="scss" scoped>
/deep/.van-field__label {
  width: 27%;
  text-align: center;
}

.van-cell,
/deep/.van-dropdown-menu__title {
  font-size: 14px;
}

/deep/.van-dropdown-menu__title {
  background: rgba(0, 0, 0, 0);
}

/deep/.van-checkbox__icon--checked .van-icon {
  background-color: transparent !important;
  border-color: #ee3f00 !important;
  color: #ee3f00 !important;
}

/deep/.van-checkbox__label {
  color: #ee3f00 !important;
}

.my_select /deep/ .van-cell__title {
  margin-left: 70px;
}

.van-ellipsis {
  font-size: 14px;
}

.view-router {
  padding-bottom: 20px;
}

/deep/ .van-picker__cancel,
/deep/ .van-picker__confirm {
  color: #ee3f00;
}

// /deep/ .van-field__label {
//   width: 70px;
// }

/deep/ .van-dropdown-menu__item {
  justify-content: flex-start;
}

/deep/ .van-dropdown-menu__title {
  padding: 0 18px 0 0;
}

.is_package /deep/ .van-cell__value {
  margin: auto 0;
}

/deep/ .van-cell-group .van-radio__label {
  line-height: 16px;
  font-size: 14px;
}

/deep/ .van-radio__icon .van-icon {
  height: 16px;
  width: 16px;
  line-height: 16px;
  margin-right: 10px;
}

/deep/ .is_package .van-icon-success:before {
  content: '';
}

.have_read_protocol {
  line-height: 20px;
  height: 20px;
  position: absolute;
}

/*this 追加 */
/deep/.van-dropdown-menu__bar {
  height: auto;
  max-height: 100%;
  box-shadow: none;
  background-color: inherit !important;

  .van-dropdown-menu__title::after {
    border-color: transparent transparent rgba(0, 0, 0, 1) rgba(0, 0, 0, 1);
  }
}
</style>
